
<?php
    header("Content-Type: text/html;charset=utf-8");
	include('./data/config.php');
    //应用APP ID
    //应用填写的网站回调域
    $my_url ='http://'.$_SERVER['SERVER_NAME'].'/user.php?mode=qqlogin';
    //Step1：获取Authorization Code
    $code = $_REQUEST["code"];//存放Authorization Code
    if(empty($code)) {
        //state参数用于防止CSRF攻击，成功授权后回调时原样带回
        $_SESSION['state'] = md5(uniqid(rand(), TRUE));
        //拼接URL
        $dialog_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=".$aik_qqappid."&redirect_uri=".urlencode($my_url)."&state=".$_SESSION['state'];
        echo("<script> top.location.href='".$dialog_url."'</script>");
    }
  
    //Step2：通过Authorization Code获取Access Token
    if($_REQUEST['state'] == $_SESSION['state'] || 1) {
        //拼接URL
        $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"."client_id=".$aik_qqappid."&redirect_uri=".urlencode($my_url)."&client_secret=".$aik_qqappkey."&code=".$code;
        $response = file_get_contents($token_url);
 
        //如果用户临时改变主意取消登录，返回true!==false,否则执行step3  
        if (strpos($response, "callback") !== false) {
            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response = substr($response, $lpos + 1, $rpos - $lpos -1);
            $msg = json_decode($response);
            if (isset($msg->error)) {
                echo "<h3>error:</h3>".$msg->error;
                echo "<h3>msg :</h3>".$msg->error_description;
                exit;
            }
        }
  
        //Step3：使用Access Token来获取用户的OpenID
        $params = array();
        parse_str($response, $params);//把传回来的数据参数变量化
        $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token'];
        $str = file_get_contents($graph_url);
        if (strpos($str, "callback") !== false) {
            $lpos = strpos($str, "(");
            $rpos = strrpos($str, ")");
            $str = substr($str, $lpos + 1, $rpos - $lpos -1);
        }
        $user = json_decode($str);//存放返回的数据 client_id ，openid
        if (isset($user->error)) {
            echo "<h3>error:</h3>".$user->error;
            echo "<h3>msg :</h3>".$user->error_description;
            exit;
        }
  
        //Step4：使用openid和access_token获取用户信息
        $user_data_url = "https://graph.qq.com/user/get_user_info?access_token={$params['access_token']}&oauth_consumer_key={$aik_qqappid}&openid={$user->openid}&format=json";
      
        $user_data = file_get_contents($user_data_url);//获取到的用户信息
  $user_data = json_decode($user_data, true);
  $user_data['openid'] = $user->openid;

      $data = array();
      $data['sex']           = $user_data["gender"]=='男'?1:2;
      $data['province']      = $user_data["province"];
      $data['city']          = $user_data["city"];
      $data['person_name']   = $user_data["nickname"];
      $data['qq_openid']     = $user_data["openid"];
      $data['qq_name']       = $user_data["nickname"];
      $data['qq_img']        = $user_data["figureurl_qq_2"];
      $data['addtime']       = date("Y-m-d H:i:s", time());
      $data['person_img']    = $user_data["figureurl_qq_2"];
      $data['signtime']      = date("Y-m-d H:i:s", time());
	  $_data['aik_user_ip'] = getIP();

	
        //以下为授权成功后的自定义操作
        if($user_data&&($data['qq_name']<>"")){
			$aik_user_name='QQ用户'.$data['qq_openid'];
			$time=time();
		$sqll = "select * from aikcms_user where aik_user_name='".$aik_user_name."'";
	    $result = mysql_query($sqll);
	    if(!! $dataa = mysql_fetch_array($result)){
		if($dataa['aik_user_on']=="1"){
		setcookie('username',$dataa['aik_user_name']);
		header('location:user.php?mode=index');
		exit();
		}else{
			alert_href('该账号已被锁定，请联系管理员！','user.php?mode=login');
		    exit();
		}
	}else{
		$sqlip="select * from aikcms_user where aik_user_ip='".getIP()."' limit 1";
	    $rowip=mysql_fetch_array(mysql_query($sqlip));
	    if((!$rowip)&&$affid){
	    $newint=get_user_int($affid)+$aik_user_affint;
	    mysql_query('UPDATE `aikcms_user` SET `aik_user_int`='.$newint.' WHERE id='.$affid.'');
	    }
		$sql = 'insert into aikcms_user ( `aik_user_name`,`aik_user_alias`, `aik_user_img`, `aik_user_qqlogin`, `aik_user_time`) values ("' . $aik_user_name . '", "' . $data['qq_name'] . '", "'.$data['qq_img'].'", "1", "'.$time.'")';
	    if (mysql_query($sql)) {
		setcookie('username',$aik_user_name);
		alert_href('QQ登录成功!', 'user.php?mode=index');
	   } else {
		alert_href('QQ登录失败，请重试或直接注册!', 'login.php');
	   }
		
}
            // ......
		//setcookie('user_name',$data['qq_name'],time()+3600 * 24 * 365); 
        //setcookie('user_password',$data['qq_img'],time()+3600 * 24 * 365); 	


         
        }else{
            echo '未知错误';
        }
    }else{
        echo("The state does not match. You may be a victim of CSRF.");
    }
?>